<?php
    /**
     * Created by PhpStorm.
     * User: timeteam
     * Date: 18-11-5
     * Time: 下午5:29
     */

    namespace app\member\behavior;

    use app\common\utils\UtilRedisBase;
    use app\member\logic\MessageTpl;
    use app\member\model\MemberModel;
    use think\Db;

    class Message
    {
        public function memberMessage($data = [])
        {
            if (isset($data['tpl_id']) && isset($data['data']) && !empty($data['data']) && (isset($data['member_id']) || $data['phone'])) {
                $Redis = UtilRedisBase::getInstance(config('redis'));
                $Tpl = $this->getTpl($data['tpl_id']);
                $MessageContent = MessageTpl::TempReplace($data['data'], $Tpl['content']);
                $msg = ['type' => $Tpl['type'],//支持那些发送类型 例如 短信 微信模板消息 等等
                    'content' => $MessageContent,];

                if (isset($data['phone'])) {
                    $member = $this->getMember(['phone' => $data['phone']]);
                    $msg['phone'] = $data['phone'];
                    $msg['member_id'] = $member['id'];
                } else {
                    $member = $this->getMember(['id' => $data['member_id']]);
                    $msg['member_id'] = $data['member_id'];
                    $msg['phone'] = $member['phone'];
                }
                $Redis->rPush('message_one', json_encode($msg));
            }
        }

        protected function getMember($where = [])
        {
            return MemberModel::where($where)->find();
        }

        protected function getTpl($tpl_id)
        {
            return Db::name('member_message_tpl')->where(['id' => $tpl_id])->find();

        }
    }